//
//  AddressSecondViewController.m
//  MyDian
//
//  Created by dllo on 16/9/26.
//  Copyright © 2016年 m. All rights reserved.
//

#import "AddressSecondViewController.h"
#import "UIView+Frame.h"
#import <ActionSheetCustomPicker.h>
#import <MJExtension.h>
@interface AddressSecondViewController ()<UITextFieldDelegate,ActionSheetCustomPickerDelegate>
@property (nonatomic, strong)UITextField *textFiledperson;
@property (nonatomic, strong)UITextField *textphoneNumber;
@property (nonatomic, strong)UIButton *buttoncity;
@property (nonatomic, strong)UITextField *textFiledaddress;
@property (nonatomic, strong)UIButton *buttonsave;
@property (nonatomic,strong) NSArray *addressArr; // 解析出来的最外层数组
@property (nonatomic,strong) NSArray *provinceArr; // 省
@property (nonatomic,strong) NSArray *countryArr; // 市
@property (nonatomic,strong) NSArray *districtArr; // 区
@property (nonatomic,assign) NSInteger index1; // 省下标
@property (nonatomic,assign) NSInteger index2; // 市下标
@property (nonatomic,assign) NSInteger index3; // 区下标
@property (nonatomic,strong) ActionSheetCustomPicker *picker; // 选择器
@property (nonatomic, strong)UILabel *labeldetailAddress;
@end

@implementation AddressSecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
      self.view.backgroundColor = [UIColor whiteColor];
      [self calculateFirstData];
      UIView *viewRed = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, 64)];
      [self.view addSubview:viewRed];
      viewRed.backgroundColor = [UIColor redColor];
      viewRed.userInteractionEnabled = YES;
      if (self.pushAddress) {
            self.labeldetailAddress.text = self.pushAddress;
      }
      if (self.selections.count) {
            self.index1 = [self.selections[0] integerValue];
            self.index2 = [self.selections[1] integerValue];
            self.index3 = [self.selections[2] integerValue];
      }
      [self letfButton];
      self.title = @"地址编辑";
      UIColor * color = [UIColor whiteColor];
      NSDictionary * dict=[NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
      self.navigationController.navigationBar.titleTextAttributes = dict;
      self.navigationController.navigationBar.barStyle = UIStatusBarStyleDefault;
      [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
      [self createaddress];
}
- (void)loadFirstData
{
      // 注意JSON后缀的东西和Plist不同，Plist可以直接通过contentOfFile抓取，Json要先打成字符串，然后用工具转换
      NSString *path = [[NSBundle mainBundle] pathForResource:@"address" ofType:@"json"];
      NSLog(@"%@",path);
      NSString *jsonStr = [NSString stringWithContentsOfFile:path usedEncoding:nil error:nil];
      NSData *data  = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
      NSError *error = nil;
      id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
      
      self.addressArr = result;
      NSMutableArray *firstName = [[NSMutableArray alloc] init];
      for (NSDictionary *dict in self.addressArr)
      {
            NSString *name = dict.allKeys.firstObject;
            [firstName addObject:name];
      }
      // 第一层是省份 分解出整个省份数组
      self.provinceArr = firstName;
}

- (void)letfButton {
      self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"btn_back"] style:UIBarButtonItemStylePlain target:self action:@selector(handleLeft)];
      
}
- (void)handleLeft {
      [self.navigationController popViewControllerAnimated:YES];
}
- (void)createaddress {
      UILabel *labelperson = [[UILabel alloc]initWithFrame:CGRectMake(15, 74, 60, 30)];
      [self.view addSubview:labelperson];
      labelperson.text = @"联 系 人";
      labelperson.font = [UIFont systemFontOfSize:15];
      labelperson.textColor = [UIColor colorWithWhite:0.600 alpha:1.000];
      _textFiledperson = [[UITextField alloc]initWithFrame:CGRectMake(80, 70, self.view.width, 40)];
      [self.view addSubview:_textFiledperson];
      _textFiledperson.tintColor = [UIColor redColor];
      UIView *viewgrayone = [[UIView alloc]initWithFrame:CGRectMake(15, 110, self.view.width, 1)];
      [self.view addSubview:viewgrayone];
      viewgrayone.backgroundColor = [UIColor colorWithWhite:0.800 alpha:1.000];
      UILabel *labelphoneNumber = [[UILabel alloc]initWithFrame:CGRectMake(15, 121, 60, 30)];
      [self.view addSubview:labelphoneNumber];
      labelphoneNumber.text = @"手机号码";
      labelphoneNumber.textColor = [UIColor colorWithWhite:0.600 alpha:1.000];
      labelphoneNumber.font = [UIFont systemFontOfSize:15];
      _textphoneNumber = [[UITextField alloc]initWithFrame:CGRectMake(80, 117, self.view.width, 40)];
      [self.view addSubview:_textphoneNumber];
      _textphoneNumber.tintColor = [UIColor redColor];
      UIView *viewtwo = [[UIView alloc]initWithFrame:CGRectMake(15, 157, self.view.width, 1)];
      [self.view addSubview:viewtwo];
      viewtwo.backgroundColor = [UIColor colorWithWhite:0.800 alpha:1.000];
      UILabel *labelcity = [[UILabel alloc]initWithFrame:CGRectMake(15, 168, 60, 30)];
      [self.view addSubview:labelcity];
      labelcity.text = @"所在城市";
      labelcity.textColor = [UIColor colorWithWhite:0.600 alpha:1.000];
      labelcity.font = [UIFont systemFontOfSize:15];
      _buttoncity = [[UIButton alloc]initWithFrame:CGRectMake(0, 158, self.view.width, 50)];
      [self.view addSubview:_buttoncity];
      [_buttoncity addTarget:self action:@selector(handleButton:) forControlEvents:UIControlEventTouchUpInside];
      UIImageView *imageViewTriangle = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ar_3x"]];
      [self.view addSubview:imageViewTriangle];
      imageViewTriangle.frame = CGRectMake(self.view.width - 40, 168, 25, 25);
      UIView *viewgraythree = [[UIView alloc]initWithFrame:CGRectMake(15, 208, self.view.width, 1)];
      [self.view addSubview:viewgraythree];
      viewgraythree.backgroundColor = [UIColor colorWithWhite:0.800 alpha:1.000];
      UILabel *labeladdress = [[UILabel alloc]initWithFrame:CGRectMake(15, 219, 60, 30)];
      [self.view addSubview:labeladdress];
      labeladdress.text = @"邮寄地址";
      labeladdress.textColor = [UIColor colorWithWhite:0.600 alpha:1.000];
      labeladdress.font = [UIFont systemFontOfSize:15];
      _textFiledaddress = [[UITextField alloc]initWithFrame:CGRectMake(80, 215, self.view.width, 40)];
      [self.view addSubview:_textFiledaddress];
      _textFiledaddress.tintColor = [UIColor redColor];
      UIView *viewgrayfour = [[UIView alloc]initWithFrame:CGRectMake(0, 255, self.view.width, 1)];
      [self.view addSubview:viewgrayfour];
      viewgrayfour.backgroundColor = [UIColor colorWithWhite:0.800 alpha:1.000];
      _buttonsave = [[UIButton alloc]initWithFrame:CGRectMake(10, 266, self.view.width - 20, 60)];
      [self.view addSubview:_buttonsave];
      _buttonsave.backgroundColor = [UIColor whiteColor];
      [_buttonsave setTitle:@"保存" forState:UIControlStateNormal];
      [_buttonsave setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
      _buttonsave.titleLabel.font = [UIFont systemFontOfSize:18];
      _buttonsave.titleLabel.font = [UIFont fontWithName:@"Helvetica-BoldOblique" size:18];
      [_buttonsave addTarget:self action:@selector(handlesave:) forControlEvents:UIControlEventTouchUpInside];
      [_buttonsave.layer setCornerRadius:5.0]; //设置矩形四个圆角半径
      _buttonsave.layer.borderColor=[UIColor colorWithWhite:0.902 alpha:1.000].CGColor;
      [_buttonsave.layer setBorderWidth:1.0];
      _textFiledperson.delegate = self;
      [_textFiledperson addTarget:self action:@selector(handlePerson:) forControlEvents:UIControlEventTouchDown];
      _labeldetailAddress = [[UILabel alloc]initWithFrame:CGRectMake(100, 167, self.view.width, 30)];
      [self.view addSubview:_labeldetailAddress];
}


- (void)handlePerson:(UITextField *)person {
}
- (void)handleButton:(UIButton *)button {
      double delayInSeconds = 0.3;
      dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
      dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            self.picker = [[ActionSheetCustomPicker alloc]initWithTitle:@"选择城市" delegate:self showCancelButton:NO origin:self.view initialSelections:@[@(self.index1),@(self.index2),@(self.index3)]];
            self.picker.tapDismissAction  = TapActionSuccess;
            self.picker.supportedInterfaceOrientations = UIDeviceOrientationLandscapeRight;
            [self.picker showActionSheetPicker];
            
             });
      [_textFiledperson resignFirstResponder];
      [_textphoneNumber resignFirstResponder];
      [_textFiledaddress resignFirstResponder];
}

- (void)handlesave:(UIButton *)save {
      
}
// 根据传进来的下标数组计算对应的三个数组
- (void)calculateFirstData
{
      // 拿出省的数组
      [self loadFirstData];
      
      NSMutableArray *cityNameArr = [[NSMutableArray alloc] init];
      // 根据省的index1，默认是0，拿出对应省下面的市
      for (NSDictionary *cityName in [self.addressArr[self.index1] allValues].firstObject) {
            
            NSString *name1 = cityName.allKeys.firstObject;
            [cityNameArr addObject:name1];
      }
      // 组装对应省下面的市
      self.countryArr = cityNameArr;
      //                             index1对应省的字典         市的数组 index2市的字典   对应市的数组
      // 这里的allValue是取出来的大数组，取第0个就是需要的内容
      self.districtArr = [[self.addressArr[self.index1] allValues][0][self.index2] allValues][0];
}

#pragma mark - UIPickerViewDataSource Implementation
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
      return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
      // Returns
      switch (component)
      {
            case 0: return self.provinceArr.count;
            case 1: return self.countryArr.count;
            case 2:return self.districtArr.count;
            default:break;
      }
      return 0;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
      double delayInSeconds = 0.1;
      dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
      dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.view endEditing:YES];
      });

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated {
      self.hidesBottomBarWhenPushed = YES;
      [_textFiledperson becomeFirstResponder];
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
      switch (component)
      {
            case 0: return self.provinceArr[row];break;
            case 1: return self.countryArr[row];break;
            case 2:return self.districtArr[row];break;
            default:break;
      }
      return nil;
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
      UILabel* label = (UILabel*)view;
      if (!label)
      {
            label = [[UILabel alloc] init];
            [label setFont:[UIFont systemFontOfSize:14]];
      }
      
      NSString * title = @"";
      switch (component)
      {
            case 0: title =   self.provinceArr[row];break;
            case 1: title =   self.countryArr[row];break;
            case 2: title =   self.districtArr[row];break;
            default:break;
      }
      label.textAlignment = NSTextAlignmentCenter;
      label.text=title;
      return label;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
      switch (component)
      {
            case 0:
            {
                  self.index1 = row;
                  self.index2 = 0;
                  self.index3 = 0;
                  //            [self calculateData];
                  // 滚动的时候都要进行一次数组的刷新
                  [self calculateFirstData];
                  [pickerView reloadComponent:1];
                  [pickerView reloadComponent:2];
                  [pickerView selectRow:0 inComponent:1 animated:YES];
                  [pickerView selectRow:0 inComponent:2 animated:YES];
            }
                  break;
                  
            case 1:
            {
                  self.index2 = row;
                  self.index3 = 0;
                  //            [self calculateData];
                  [self calculateFirstData];
                  [pickerView selectRow:0 inComponent:2 animated:YES];
                  [pickerView reloadComponent:2];
            }
                  break;
            case 2:
                  self.index3 = row;
                  break;
            default:break;
      }
}
// 点击done的时候回调
- (void)actionSheetPickerDidSucceed:(ActionSheetCustomPicker *)actionSheetPicker origin:(id)origin
{
      NSMutableString *detailAddress = [[NSMutableString alloc] init];
      if (self.index1 < self.provinceArr.count) {
            NSString *firstAddress = self.provinceArr[self.index1];
            [detailAddress appendString:firstAddress];
      }
      if (self.index2 < self.countryArr.count) {
            NSString *secondAddress = self.countryArr[self.index2];
            [detailAddress appendString:secondAddress];
      }
      if (self.index3 < self.districtArr.count) {
            NSString *thirfAddress = self.districtArr[self.index3];
            [detailAddress appendString:thirfAddress];
      }
      // 此界面显示
      self.labeldetailAddress.text = detailAddress;
      // 回调到上一个界面
//      self.myBlock(detailAddress,@[@(self.index1),@(self.index2),@(self.index3)]);
}


- (NSArray *)provinceArr
{
      if (_provinceArr == nil) {
            _provinceArr = [[NSArray alloc] init];
      }
      return _provinceArr;
}
-(NSArray *)countryArr
{
      if(_countryArr == nil)
      {
            _countryArr = [[NSArray alloc] init];
      }
      return _countryArr;
}

- (NSArray *)districtArr
{
      if (_districtArr == nil) {
            _districtArr = [[NSArray alloc] init];
      }
      return _districtArr;
}

-(NSArray *)addressArr
{
      if (_addressArr == nil) {
            _addressArr = [[NSArray alloc] init];
      }
      return _addressArr;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
